// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// u [author] rhyme_lph
// V [email]  rhymelph@gmail.com
// E [github] https://github.com/rhymelph

import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/entities/product_entity.dart';
import 'package:finance_app/src/http_service/http_product_service.dart';
import 'package:finance_app/src/mixin/format_group_map_mixin.dart';
import 'package:finance_app/src/mixin/search_data_list_mixin.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:flutter/material.dart';

class ProductBomListProvider extends BaseProvider<List<ProductBoms>>
    with
        SearchDataListMixin<List<ProductBoms>>,
        FormatGroupMapLocalMixin<ProductBoms> {
  ProductBoms currentSelect;

  List<ProductBoms> filterData = [];

  @override
  Future get dataFuture => HttpProductService.productBomList();

  void onShowAddProduct() async {
    final result =
        await Routes.navigateTo(RouterGenProviders.newProductPage, params: {
      'isPro': true,
    });
    if (result != null) {
      obtainContext?.call((context) {
        ProductEntity entity = result as ProductEntity;
        Navigator.of(context).pop(ProductBoms().fromJson(entity.toJson()));
      });
    }
  }

  void onSelectProduct(ProductBoms data) {
    if (currentSelect?.id == data.id) return;
    currentSelect = data;
    update();
    obtainContext?.call((context) {
      Navigator.of(context).pop(currentSelect);
    });
  }

  @override
  FutureOr<List<ProductBoms>> transformData(List<ProductBoms> d, bool isCache) {
    groupMap.clear();
    List<ProductBoms> boms = [];
    if (filterData != null && filterData.length > 0) {
      for (final item in d) {
        final finder = filterData.firstWhere((element) => element.id == item.id,
            orElse: () => null);
        if (finder == null || item.id == currentSelect?.id) {
          boms.add(item);
        }
      }
    } else {
      boms = d;
    }
    contactToMap(boms);
    return boms;
  }

  void contactToMap(List<ProductBoms> list) {
    sortGroupToMap(list,
        sort: (a, b) => sortNameFirst(a, b, (t) => t.name),
        group: (a) => groupFirstName(a, (t) => t.name, "*"),
        filter: (a) => onFilterSearch(searchController.text, a.name));
  }

  @override
  void searchRefreshData(searchData) {
    transformData(data, false);
    update();
  }

  void onShowAddProductName(String text) async {
    final result =
        await Routes.navigateTo(RouterGenProviders.newProductPage, params: {
      'isPro': true,
      'text': text,
    });
    if (result != null) {
      obtainContext?.call((context) {
        ProductEntity entity = result as ProductEntity;
        Navigator.of(context).pop(ProductBoms().fromJson(entity.toJson()));
      });
    }
  }
}
